package com.wm.web.action;

import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;

import com.wm.bean.User;
import com.wm.comm.Code;
import com.wm.comm.Constant;
import com.wm.comm.EmailUtil;
import com.wm.comm.MD5;
import com.wm.service.UserService;
import com.wm.web.servlet.UserSession;

public class PasswordAction extends BaseAction implements SessionAware {
	private static final Log logger = LogFactory.getLog(PasswordAction.class);
	
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	private Map session;

	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}
	
	private String password;
	private String oldPwd;
	private String result;
	private String username;
	private String verifycode;
	private String ticket;
	private String error;

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getOldPwd() {
		return oldPwd;
	}

	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getVerifycode() {
		return verifycode;
	}

	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}

	public String getTicket() {
		return ticket;
	}

	public void setTicket(String ticket) {
		this.ticket = ticket;
	}
	
	public String execute() {
		try {
			return this.executeMethod(this.getAction());
		} catch (Exception e) {
			logger.error(e);
			return INPUT;
		}
	}

	/**
	 * 初始页
	 */
	public String index(){
		if(this.getSession().get(Constant.USER_SESSION_KEY)==null){
			return "default";
		}
		return "index";
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	public String update(){
		if(this.getSession().get(Constant.USER_SESSION_KEY)==null){
			this.setError("1");
			return "default";
		}
		if(this.getPassword()==null ||this.getPassword().trim().equals("")||this.getPassword().length()>20){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		if(!checkPassword(this.getPassword())){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		UserSession us = (UserSession)this.getSession().get(Constant.USER_SESSION_KEY);
		User u = this.getUserService().findUserById(us.getUid());
		MD5 md5 = new MD5();
		System.out.println(md5.getMD5ofStr(this.getOldPwd()));
		if(u!=null && u.getUserPwd().equals(md5.getMD5ofStr(this.getOldPwd()))){
			u.setUserPwd(md5.getMD5ofStr(this.getPassword()));
			u.setUserPwdShow(this.getPassword());
			this.getUserService().updateUser(u);
			this.addFieldError("error", this.getText("error.password.ok"));
		}else{
			this.addFieldError("error", this.getText("error.oldPwd"));
		}
		this.setError("1");
		return "index";
	}
	
	/**
	 * 进入找回密码页
	 * @return
	 */
	public String password(){
		return "getPassword";
	}
	
	/**
	 * 发送带有重置新密码连接的email
	 * @return
	 */
	public String passwordEmail(){
		//验证码正确
		if(!getSessionAuthCode().equalsIgnoreCase(verifycode)){
			this.addFieldError("error", this.getText("error.autherror"));
			this.setError("1");
			return "getPassword";
		}
		if(this.getUsername()==null ||this.getUsername().trim().equals("")||this.getUsername().length()>30){
			this.addFieldError("error", this.getText("error.username"));
			this.setError("1");
			return "getPassword";
		}
		
		User user = this.getUserService().findUserByUserName(this.getUsername());
		if(user==null){
			this.addFieldError("error", this.getText("email.username.error"));
			this.setError("1");
			return "getPassword";
		}else{
			//加密URL
			Date dt= new Date();
			Long time= dt.getTime();
			Code code = new Code();
			String urlstr = code.enCode((username+"`"+time.toString()).getBytes());
			//发邮件
			String subject = Constant.WEB_NAME+" – 密码重置";
			String msg = "我们收到了您的密码重置请求。请点击该链接重置您的密码：<br>"
			+Constant.WEB_URL+"password.action?action=newPassword&ticket="+urlstr+"<br>"
			+"如上面的链接无法点击，请复制以下链接，粘贴到浏览器的地址栏内，然后按“回车”键<br>"
			+"请您在30分钟内点击以上链接重置您的密码，如果超出时效，请到"+Constant.WEB_URL+"重新申请密码找回。 <br>"
			+"如果您要放弃以上修改，或未曾申请密码重置，请忽略并/或删除本邮件。 <br>"
			+"（为了保证您的账户安全，您在网站上点击“找回密码”后，请在30分钟内完成重置密码的操作。超过30分钟地址将失效，给您带来的不便敬请原谅。）";;
			EmailUtil.sendEmail(Constant.MAIL_HOST_NAME, Constant.MAIL_CHARSET, user.getUserEmail(), Constant.MAIL_FROM_MAIL, Constant.MAIL_FROM_NAME, Constant.MAIL_FROM_USERNAME, Constant.MAIL_FROM_PASSWORD, subject, msg, msg);
			this.addFieldError("error", this.getText("email.goemail"));
			this.setError("1");
		}
		
		return "getPasswordClew";
	}
	
	/**
	 * 重置密码
	 * @return
	 */
	public String newPassword(){
		Code code = new Code();
		String urlstr = new String(code.deCode(ticket));
		String[] url = urlstr.split("`");
		User user = this.getUserService().findUserByUserName(url[0]);
		if(user!=null){
			Date dt= new Date();
			Long time= dt.getTime();
			long between=(time-new Long(url[1]))/1000;//除以1000是为了转换成秒
			if(between>1800){
		   		//发邮件
				String subject = Constant.WEB_NAME+" – 密码找回超时";
				String msg = "对不起，您的地址无效，如需密码找回请到"+Constant.WEB_URL+"重新申请<br>"
				+"（为了保证您的账户安全，您在网站上点击“找回密码”后，请在30分钟内完成重置密码的操作。超过30分钟地址将失效，给您带来的不便敬请原谅。）";
				EmailUtil.sendEmail(Constant.MAIL_HOST_NAME, Constant.MAIL_CHARSET, user.getUserEmail(), Constant.MAIL_FROM_MAIL, Constant.MAIL_FROM_NAME, Constant.MAIL_FROM_USERNAME, Constant.MAIL_FROM_PASSWORD, subject, msg, msg);
				this.addFieldError("error", this.getText("email.url.error"));
				this.setError("1");
				return "getPasswordClew";
		   	}else{
			   	//生成6位新密码
		   		String newPassword="";
		   		while(newPassword.length()<6){
		   			newPassword+=(int)(Math.random()*10);
		   		}
		   		//修改密码
		   		MD5 md5 = new MD5();
		   		user.setUserPwd(md5.getMD5ofStr(newPassword));
		   		user.setUserPwdShow(newPassword);
		   		this.getUserService().updateUser(user);
				//发邮件
				String subject = Constant.WEB_NAME+" – 您的新密码";
				String msg = "您的"+Constant.WEB_NAME+"账号的新密码为：" + newPassword;
				EmailUtil.sendEmail(Constant.MAIL_HOST_NAME, Constant.MAIL_CHARSET, user.getUserEmail(), Constant.MAIL_FROM_MAIL, Constant.MAIL_FROM_NAME, Constant.MAIL_FROM_USERNAME, Constant.MAIL_FROM_PASSWORD, subject, msg, msg);
				this.addFieldError("error", this.getText("email.ok"));
				this.setError("1");
				return "getPasswordClew";
		   	}
		}
		return "getPasswordClew";
	}
	
	private String getSessionAuthCode() {
        String auth = (String) this.getSession().get("authCode");
        if(StringUtils.isBlank(auth)){
        	return "";
        }else{
        	return auth;
        }
    }
	
	public static boolean checkPassword(String password) {
		  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+";
		  String regex = "^[a-zA-Z0-9_]+$";
		  Pattern p = Pattern.compile(regex);
		  Matcher m = p.matcher(password);
		  return m.matches();
		}

}
